package dpe;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class EngineLoader {
	private Engine engine;
	private Game game;

	public EngineLoader(Engine engine) {
		this.engine = engine;
	}

	public void loadGame(String fileName) {
		try {
			File file = new File(fileName);
			Engine.log(0, "Reading file '" + file.getName() + "'");
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder;
			builder = factory.newDocumentBuilder();
			Document document = builder.parse(file);
			document.getDocumentElement().normalize();

			readElement(document.getDocumentElement());
			
			engine.startGame();
		} catch (Exception e) {
			Engine.log(2, "Exception occured when trying to read file '" + fileName + "'");
			e.printStackTrace();
			Engine.exit(1);
		}
	}

	private void readElement(Element e) {
		NodeList nodelist = e.getChildNodes();
		String tagName = e.getTagName().toLowerCase();
		if (tagName.equals("game")) {
			game = engine.newGame();
			if (e.hasAttribute("verision")) {
				game.setVerision(e.getAttribute("verision"));
			}
		} else if (tagName.equals("settings")) {
			if (e.hasAttribute("znear")) {
				game.setZNear(Float.parseFloat(e.getAttribute("znear")));
			}
			if (e.hasAttribute("zfar")) {
				game.setZFar(Float.parseFloat(e.getAttribute("zfar")));
			}
			if (e.hasAttribute("fov")) {
				game.setFov(Float.parseFloat(e.getAttribute("fov")));
			}
		} else if (tagName.equals("display")) {
			if (e.hasAttribute("width")) {
				game.setDisplayWidth(Integer.parseInt(e.getAttribute("width")));
			}
			if (e.hasAttribute("height")) {
				game.setDisplayHeight(Integer.parseInt(e.getAttribute("height")));
			}
			if (e.hasAttribute("title")) {
				game.setDisplayTitle(e.getAttribute("title"));
			}
			if (e.hasAttribute("fullscreen")) {
				game.setDisplayFullscreen(Boolean.parseBoolean(e.getAttribute("fullscreen")));
			}
		}
		
		if (e.hasChildNodes()) {
			for (int i = 0; i < nodelist.getLength(); i++) {
				Node n = nodelist.item(i);
				if (n.getNodeType() == Node.ELEMENT_NODE) {
					readElement((Element) n);
				}
			}
		}
	}
}
